using System;
using ColorBox4Sitecore.Colorbox;
using Sitecore.Data.Fields;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;

namespace ColorBox4Sitecore.Helpers
{
    public static class ColorboxUnitHelper
    {
        public static ColorboxUnit GetColorboxUnitValueFromField(this Item item, string fieldName)
        {
            return item.GetColorboxUnitValueFromField(fieldName, ColorboxUnit.None);
        }

        public static ColorboxUnit GetColorboxUnitValueFromField(this Item item, string fieldName, ColorboxUnit defaultValue)
        {
            if (item == null)
            {
                Log.Error("ColorboxUnitHelper.GetColorboxUnitValueFromField(): item is null", typeof(ColorboxUnitHelper));
                throw new ArgumentNullException("item");
            }

            var fld = (InternalLinkField)item.Fields[fieldName];


            if (fld == null || fld.TargetItem == null)
                return defaultValue;

            switch (fld.TargetItem.Name)
            {
                case "None":
                    return ColorboxUnit.None;
                case "Percentages":
                    return ColorboxUnit.Percentage;
                case "Pixels":
                    return ColorboxUnit.Pixels;
                default:
                    return defaultValue;
            }
        }

        public static string ToJsString(ColorboxUnit unit)
        {
            switch (unit)
            {
                case ColorboxUnit.None:
                case ColorboxUnit.Pixels:
                    return string.Empty;
                case ColorboxUnit.Percentage:
                    return "%";
                default:
                    return string.Empty;
            }
        }
    }
}